class RequesterController < ApplicationController

  require 'json'
  require 'rest_client'

  def perform
    @record = ApiRecord.find(params[:id])
    @request_headers = headers
    case @record.request_method
    when "get"
      response = RestClient.get "#{host}#{request_path}", @request_headers
    when "post"
      response = RestClient.post "#{host}#{request_path}", values, @request_headers
    else
      # todo
    end
    @host = host
    @request_path = request_path
    @response_data = get_data(response)
  end

  private

  def values
    result = JSON.parse(@record.values) rescue nil
    return result if result
    set_values = "result = " + @record.values
    eval(set_values)
    result
  end

  def headers
    result = @record.headers.presence || "{}"
    result = result.sub("authorization:", "\"authorization\":").sub("#auth_token#", "\"" + auth_token + "\"")
    result = JSON.parse(result)
    result
  end

  def host
    development? ? "http://10.18.128.220:3005" : "https://api.weplus.com"
  end

  def request_path
    @record.request_path
  end

  def development?
    params[:env] != "production"
  end

  def production?
    !development?
  end

  def env
    params[:env].presence || "development"
  end

  def auth_token
    if development?
      auth_token_development("17612126121", "kkkkkk")
    else
      auth_token_production("17612126121", "")
    end
  end

  # auth_token_development 和 auth_token_production 两个方法有重复代码，以后优化
  def auth_token_development(mobile, passwd)
    return session[:auth_token_development] if session[:auth_token_development]
    cur_values = "{ \"data\": { \"type\": \"sessions\", \"attributes\": { \"mobile\": \"#{mobile}\", \"password\": \"#{passwd}\" } } }"
    cur_headers = { :content_type => "application/vnd.api+json" }
    cur_request_path = "/v1/sessions"
    response = RestClient.post "#{host}#{cur_request_path}", cur_values, cur_headers
    session[:auth_token_development] = get_data(response)["attributes"]["auth_token"]
  end

  def auth_token_production(mobile, passwd)
    return session[:auth_token_production] if session[:auth_token_production]
    cur_values = "{ \"data\": { \"type\": \"sessions\", \"attributes\": { \"mobile\": \"#{mobile}\", \"password\": \"#{passwd}\" } } }"
    cur_headers = { :content_type => "application/vnd.api+json" }
    cur_request_path = "/v1/sessions"
    response = RestClient.post "#{host}#{cur_request_path}", cur_values, cur_headers
    session[:auth_token_production] = get_data(response)["attributes"]["auth_token"]
  end

  def get_data(response)
    JSON.parse(response.body)["data"]
  end

end
